import 'package:flutter/material.dart';
import 'package:flutter_chat_ui/pages/onnx/input_widgets/onnx_send_button_view.dart';

import 'onnx_center_area_view.dart';
import 'onnx_toggle_buttons_view.dart';

/// 聊天输入栏状态枚举
enum ChatInputMode {
  keyboard, // 键盘模式
  voice, // 语音模式
}

/// 发送按钮状态枚举
enum SendButtonState {
  disabled, // 禁用状态（灰色）
  enabled, // 可用状态
  loading, // 加载状态（显示暂停图标）
}

///
/// 聊天底部工具条
///
class OnnxTalkBarToolsView extends StatefulWidget {
  /// 是否禁用输入（例如初始化期间）
  final bool isDisabled;

  /// 是否正在发送中
  final ValueNotifier<bool> isResponding;

  /// 发送消息回调
  final ValueChanged<String>? onSendMessage;

  /// 开始语音录制回调
  final VoidCallback? onStartVoiceRecord;

  /// 结束语音录制回调
  final VoidCallback? onEndVoiceRecord;

  /// 取消发送回调（点击暂停按钮时）
  final VoidCallback? onCancelSend;

  const OnnxTalkBarToolsView({
    super.key,
    required this.isResponding,
    this.isDisabled = false,
    this.onSendMessage,
    this.onStartVoiceRecord,
    this.onEndVoiceRecord,
    this.onCancelSend,
  });

  @override
  State<OnnxTalkBarToolsView> createState() => _AgentTalkBarToolsViewState();
}

class _AgentTalkBarToolsViewState extends State<OnnxTalkBarToolsView> {
  late final TextEditingController _textController;
  late final FocusNode _focusNode;

  final ValueNotifier<ChatInputMode> _inputModeNotifier = ValueNotifier(ChatInputMode.keyboard);
  final ValueNotifier<SendButtonState> _sendButtonStateNotifier = ValueNotifier(SendButtonState.disabled);
  final ValueNotifier<bool> _keyboardVisibilityNotifier = ValueNotifier(false);

  @override
  void initState() {
    super.initState();
    _textController = TextEditingController();
    _focusNode = FocusNode();

    // 监听文本变化
    _textController.addListener(_onTextChanged);

    // 监听焦点变化来检测键盘状态
    _focusNode.addListener(_onFocusChanged);

    // 监听外部响应状态变化
    widget.isResponding.addListener(_onRespondingChanged);
  }

  @override
  void didUpdateWidget(OnnxTalkBarToolsView oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 如果外部响应状态监听器发生变化，需要重新绑定
    if (widget.isResponding != oldWidget.isResponding) {
      oldWidget.isResponding.removeListener(_onRespondingChanged);
      widget.isResponding.addListener(_onRespondingChanged);
    }
  }

  @override
  void dispose() {
    _textController.dispose();
    _focusNode.dispose();
    _inputModeNotifier.dispose();
    _sendButtonStateNotifier.dispose();
    _keyboardVisibilityNotifier.dispose();
    _textController.removeListener(_onTextChanged);
    _focusNode.removeListener(_onFocusChanged);
    widget.isResponding.removeListener(_onRespondingChanged);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<bool>(
      valueListenable: _keyboardVisibilityNotifier,
      builder: (context, isKeyboardVisible, child) {
        return AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          padding: EdgeInsets.only(
            left: 12,
            right: 12,
            top: 12,
            bottom: isKeyboardVisible ? 12 : 0,
          ),
          decoration: const BoxDecoration(
            color: Color(0xFFF7F7F7),
          ),
          child: SafeArea(
            top: false,
            child: Opacity(
              opacity: widget.isDisabled ? 0.5 : 1.0,
              child: IgnorePointer(
                ignoring: widget.isDisabled,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    /// 左侧切换按钮
                    RepaintBoundary(
                      child: OnnxToggleButtonsView(
                        inputModeNotifier: _inputModeNotifier,
                        onToggle: _handleModeToggle,
                      ),
                    ),

                    /// 中间输入区域
                    const SizedBox(width: 12),
                    Expanded(
                      child: RepaintBoundary(
                        child: OnnxCenterAreaView(
                          inputModeNotifier: _inputModeNotifier,
                          textEditingController: _textController,
                          focusNode: _focusNode,
                          onSubmit: _handlerSendMessage,
                          onStartVoiceRecord: widget.onStartVoiceRecord,
                          onEndVoiceRecord: widget.onEndVoiceRecord,
                        ),
                      ),
                    ),

                    /// 右侧发送按钮
                    const SizedBox(width: 12),
                    RepaintBoundary(
                      child: OnnxSendButtonView(
                        sendButtonStateNotifier: _sendButtonStateNotifier,
                        onSendMessage: _handlerSendMessage,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  ///
  /// 监听文本变化
  ///
  void _onTextChanged() => _updateSendButtonState();

  ///
  /// 监听焦点变化
  ///
  void _onFocusChanged() {
    final newKeyboardState = _focusNode.hasFocus && _inputModeNotifier.value == ChatInputMode.keyboard;
    if (_keyboardVisibilityNotifier.value != newKeyboardState) {
      _keyboardVisibilityNotifier.value = newKeyboardState;
    }
  }

  ///
  /// 监听外部响应状态变化
  ///
  void _onRespondingChanged() => _updateSendButtonState();

  ///
  /// 处理模式切换
  ///
  void _handleModeToggle(ChatInputMode mode) {
    if (mode == ChatInputMode.voice) {
      // 切换到语音模式；收起键盘
      _focusNode.unfocus();
    } else {
      // 切换到键盘模式；使用 WidgetsBinding 确保在下一帧聚焦
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted && mode == ChatInputMode.keyboard) {
          _focusNode.requestFocus();
        }
      });
    }
  }

  ///
  /// 更新发送按钮状态
  ///
  void _updateSendButtonState() {
    final hasText = _textController.text.trim().isNotEmpty;
    final isResponding = widget.isResponding.value;
    final isDisabled = widget.isDisabled;

    SendButtonState newState;
    if (isDisabled || isResponding) {
      newState = isResponding ? SendButtonState.loading : SendButtonState.disabled;
    } else if (hasText) {
      newState = SendButtonState.enabled;
    } else {
      newState = SendButtonState.disabled;
    }

    if (_sendButtonStateNotifier.value != newState) {
      _sendButtonStateNotifier.value = newState;
    }
  }

  ///
  /// 发送消息
  ///
  void _handlerSendMessage() {
    final currentState = _sendButtonStateNotifier.value;

    if (currentState == SendButtonState.enabled) {
      final message = _textController.text.trim();

      if (message.isNotEmpty) {
        widget.onSendMessage?.call(message);
        _textController.clear();
        // 发送后立即更新状态
        _updateSendButtonState();
      }
    } else if (currentState == SendButtonState.loading) {
      // 点击暂停按钮
      widget.onCancelSend?.call();
    }
  }
}
